﻿using Library.Core.Application.IInfrastructure;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace SMS.HangFireApi.App_Start
{
    public class CustomJwtEvents : JwtBearerEvents
    {
        private readonly IJwtFactory _jwtFactory;
        private readonly ICurrentUserInfo _currentUserInfo;


        public CustomJwtEvents(IJwtFactory jwtFactory, ICurrentUserInfo currentUserInfo)
        {
            _jwtFactory = jwtFactory;
            _currentUserInfo = currentUserInfo;

        }
        public override async Task TokenValidated(TokenValidatedContext context)
        {

            _jwtFactory.Token = context.SecurityToken as JwtSecurityToken;
            _currentUserInfo.UserId = Guid.Parse(_jwtFactory.Token.Claims.SingleOrDefault(x => x.Type.Equals("Id")).Value);
            _currentUserInfo.UserName = _jwtFactory.Token.Claims.SingleOrDefault(x => x.Type.Equals(ClaimTypes.Name)).Value;
            if (await _jwtFactory.TokenIsInInvalid(null))
            {
                context.Fail(string.Empty);
                context.Response.OnStarting(async () =>
                {
                    //context.Response.StatusCode = 401;
                    context.Response.ContentType = "text/plain;charset=utf-8";
                    await context.Response.WriteAsync("该Token已失效，请重新登陆！");
                });
            }
            await base.TokenValidated(context);
        }
        public override Task AuthenticationFailed(AuthenticationFailedContext context)
        {

            return base.AuthenticationFailed(context);
        }
        public override Task Forbidden(ForbiddenContext context)
        {
            return base.Forbidden(context);
        }
        public override Task Challenge(JwtBearerChallengeContext context)
        {
            return base.Challenge(context);
        }

        public override Task MessageReceived(MessageReceivedContext context)
        {
            string token = context.HttpContext.Request.Cookies["access_token"];
            if (!string.IsNullOrEmpty(token))
            {
                context.Token = token;
            }
            return Task.CompletedTask;
        }
    }
}
